import re

import requests

# 实例化一个session进行长连接，使得不用每次都需要request.post发送请求
from ..entity.Account import Account

session = requests.session()
UserAgent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Mobile Safari/537.36"
header = {
    "Host": "juejin.im",
    "Referer": "https://juejin.im/",
    "User-Agent": UserAgent
}


def juejin_login(account, password):
    if re.match("^1\d{10}", account):
        print("手机号码登陆")
        post_url = "https://juejin.im/auth/type/phoneNumber"
        post_data = {
            "phoneNumber": account,
            "password": password
        }
        response_text = session.post(post_url, data=post_data, headers=header)
        # 将cookie缓存到本地
        response_json = response_text.json()
        if (response_text.status_code == 200):
            token = response_json['token']
            userId = response_json['userId']
            clientId = str(response_json['clientId'])
            login_account = Account(userId, token, clientId)
            return login_account


def get_article_interface_by_rank(login_account):
    str = "https://timeline-merger-ms.juejin.im/v1/get_entry_by_rank?src=web&uid=" + login_account.getUserId() + "&device_id=" + login_account.clientId + "&token=" + login_account.getToken().replace(
        '=', '%3D') + "&limit=100&category=all&recomment=1"
    response = session.get(
        str)
    response_json = response.json()
    return response_json


def get_article_interface_by_time(login_account):
    str = "https://timeline-merger-ms.juejin.im/v1/get_entry_by_timeline?src=web&uid=" + login_account.getUserId() + "&device_id=" + login_account.clientId + "&token=" + login_account.getToken().replace(
        '=', '%3D') + "&limit=100&category=all&recomment=1"
    response = session.get(
        str)
    response_json = response.json()
    return response_json


def get_infomation(login_account):
    result = get_article_interface_by_rank(login_account=login_account)
    list = result['d']['entrylist']
    return list
